#include "CmdGit.h"

bool git_init(std::string &name, std::string &email)
{
    // 构建命令字符串
    std::string init_cmd = "git init";
    std::string config_name_cmd = "git config user.name \"" + name + "\"";
    std::string config_email_cmd = "git config user.email \"" + email + "\"";

    if (system(init_cmd.c_str()) != 0)
    {
        endwin();
        std::cerr << "Initialization failure" << std::endl;
        return false;
    }

    if (system(config_name_cmd.c_str()) != 0)
    {
        endwin();
        std::cerr << "Failed to set user name" << std::endl;
        return false;
    }

    if (system(config_email_cmd.c_str()) != 0)
    {
        endwin();
        std::cerr << "Email setup failed" << std::endl;
        return false;
    }

    return true;
}

//add
bool git_add()
{
    std::string add_cmd = "git add . > /dev/null 2>&1";

    if (system(add_cmd.c_str()) != 0)
    {
        endwin();
        std::cerr << "Failed to add files to staging area" << std::endl;
        return false;
    }

    return true;
}

//commit
bool git_commit(const std::string &message)
{
    std::string commit_cmd = "git commit -m \"" + message + "\" > /dev/null 2>&1";

    if (system(commit_cmd.c_str()) != 0)
    {
        endwin();
        std::cerr << "Commit failed" << std::endl;
        return false;
    }

    return true;
}

// 添加远程仓库
bool git_remote_add(const std::string &url)
{
    std::string cmd = "git remote add origin " + url + " > /dev/null 2>&1";
    if (system(cmd.c_str()) != 0)
    {
        endwin();
        std::cerr << "Failed to add remote repository" << std::endl;
        return false;
    }
    return true;
}

// 推送
bool git_push()
{
    std::string push_cmd = "git push origin master > /dev/null 2>&1";

    if (system(push_cmd.c_str()) != 0)
    {
        endwin();
        std::cerr << "Push failed" << std::endl;
        return false;
    }

    return true;
}

// 拉取
bool git_pull()
{

    if (system("git diff --quiet --exit-code") != 0)
    {

        if (system("git add -A > /dev/null 2>&1") != 0)
        {
            endwin();
            std::cerr << "Failed to submit, manually process uncommitted changes" << std::endl;
            return false;
        }

        if (system("git commit -m \"Auto-commit before pull\" > /dev/null 2>&1") != 0)
        {
            endwin();
            std::cerr << "Failed to submit, manually process uncommitted changes" << std::endl;
            return false;
        }

    }

    std::string pull_cmd = "git pull origin master > /dev/null 2>&1";

    if (system(pull_cmd.c_str()) != 0)
    {
        endwin();
        std::cerr << "Pull failed" << std::endl;
        return false;
    }

    return true;
}
